<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 400px;" class="filter-item" placeholder="serverName" v-model="listQuery.filterItem">
      </el-input>
      <el-button class="filter-item" type="primary"  icon="el-icon-search" @click="handleFilter">search</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">add</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='ID' width="95">
        <template slot-scope="scope">
          {{ 1 + scope.$index + ((listQuery.page -1 ) * listQuery.limit) }}
        </template>
      </el-table-column>
      <el-table-column label="Server">
        <template slot-scope="scope">
          {{scope.row.server_name}}
        </template>
      </el-table-column>
      <el-table-column label="Applicant" width="110" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.applicant_name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="Cpu" width="110" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.cpu}}</span>
        </template>
      </el-table-column>
      <el-table-column label="Memory" width="110" align="center">
        <template slot-scope="scope">
          {{scope.row.memory}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="Status" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{scope.row.status}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="Hard Disk" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.hard_disk}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="actions" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.$index)">edit
          </el-button>
          <el-button @click="handleDelete(scope.row.server_name)" size="mini" type="danger">delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="tempServer" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        
        <el-form-item label="Name" prop="server_name">
          <el-input :disabled="dialogStatus == 'update'" v-model="tempServer.server_name"></el-input>
        </el-form-item>
        <el-form-item label="CPU"  prop="cpu">
          <el-input v-model="tempServer.cpu"></el-input>
        </el-form-item>
        <el-form-item label="Memory"  prop="memory">
          <el-select class="filter-item" v-model="tempServer.memory" placeholder="Please select">
            <el-option v-for="item in  memorySize" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="HardDisk"  prop="hard_disk">
          <el-input v-model="tempServer.hard_disk"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">Confirm</el-button>
        <el-button v-else type="primary" @click="updateData">Confirm</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getServerList, createServer, updateServer, deleteServer } from '@/api/server'

export default {
  name: 'serverTable',
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        filterItem: null,
        type: null,
        status: null,
        sort: null
      },
      currentRow: 0,
      memorySize: ['8G', '16G', '32G', '64G', '128G'],
      tempServer: {
        serverName: '',
        cpu: '',
        memory: '',
        hard_disk: ''
      },
      importanceOptions: [1, 2, 3],
      serverName: '',
      downloadLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit Server',
        create: 'Create Server'
      },
      rules: {
        server_name: [{ required: true, message: 'server name is required', trigger: 'change' }],
        cpu: [{ required: true, message: 'cpu is required', trigger: 'change' }],
        memory: [{ required: true, message: 'memory is required', trigger: 'blur' }],
        hard_disk: [{ required: true, message: 'hard disk is required', trigger: 'blur' }]
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }]
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    // this.fetchData()
    this.getList()
  },
  methods: {
    // fetchData() {
    //   this.listLoading = true
    //   getServer().then(response => {
    //     this.list = response
    //     this.listLoading = false
    //   })
    // },
    getList() {
      this.listLoading = true
      getServerList(this.listQuery).then(response => {
        this.list = response.dataList
        this.total = response.total
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      var lastPage = Math.ceil(this.total / val)
      if (lastPage < this.listQuery.page) {
        this.listQuery.page = lastPage
      }
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // getServerList() {
    //   findByName(this.serverName).then(response => {
    //     this.list = response
    //     this.listLoading = false
    //   })
    // },
    handleFilter() {
      this.getList()
    },
    handleUpdate(index) {
      this.$router.push({
        name: 'ServerDetail',
        params: {
          'server': this.list[index],
          'type': 'update'
        }
      })
      // this.currentRow = index;
      // this.tempServer = Object.assign({}, this.list[index]) // copy obj
      // this.dialogStatus = 'update'
      // this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createServer(this.tempServer).then(() => {
            this.list.unshift(this.tempServer)
            this.dialogFormVisible = false
            this.$notify({
              title: 'success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateServer(this.tempServer).then(() => {
            this.list.splice(this.currentRow, 1, this.tempServer)
            this.dialogFormVisible = false
            this.$notify({
              title: 'success',
              message: 'Modify Success!',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    resetTemp() {
      this.tempServer = {
        serverName: '',
        cpu: '',
        memory: '',
        hard_disk: ''
      }
    },
    handleCreate() {
      this.$router.push({
        name: 'ServerDetail',
        params: {
          'server': {},
          'type': 'create'
        }
      })
      // this.resetTemp()
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    handleDelete(deleteServerName) {
      deleteServer(deleteServerName).then(response => {
        if (response) {
          this.$notify({
            title: 'success',
            message: 'Delete Success!',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: 'error',
            message: 'Delete Failed!',
            type: 'error',
            duration: 2000
          })
        }
        this.getList()
      })
    }
  }
}
</script>
